package com.imedway.ihe.dtz.xds.dao.camel;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml30.RetrieveDocumentSetRequestType.DocumentRequest;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.imedway.ihe.dtz.xds.entity.camel.XdsDocumentEntryPO;
import com.imedway.ihe.dtz.xds.vo.RetrievedDocumentVO;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author dtz <br/>
 * @date 2024/7/4
 */
@Slf4j
@Repository
public class Iti43Dao_CAMEL {
		
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	public RetrievedDocumentVO findRetrievedDocument(DocumentRequest documentRequest) throws SQLException {
		NamedParameterJdbcTemplate jdbc = new NamedParameterJdbcTemplate(jdbcTemplate);
		StringBuilder sql = new StringBuilder();
		Map<String, String> map = new HashMap<String, String>();
		sql.append(" SELECT * FROM camel_xdsdocumententry where 1=1 ");
		sql.append("  and uniqueId=:uniqueId ");
		map.put("uniqueId", documentRequest.getDocumentUniqueId());
		if (StringUtils.hasText(documentRequest.getHomeCommunityId())) {
			sql.append("  and homeCommunityId=:homeCommunityId ");
			map.put("homeCommunityId", documentRequest.getHomeCommunityId());
		}
		if (StringUtils.hasText(documentRequest.getRepositoryUniqueId())) {
			sql.append("  and repositoryUniqueId=:repositoryUniqueId ");
			map.put("repositoryUniqueId", documentRequest.getRepositoryUniqueId());
		}
		log.info(sql.toString());
		XdsDocumentEntryPO xdsDocumentEntryPO = jdbc.queryForObject(sql.toString(), map,
				new BeanPropertyRowMapper<>(XdsDocumentEntryPO.class));

		log.info(JSONUtil.toJsonStr(xdsDocumentEntryPO));
		RetrievedDocumentVO retrievedDocumentVO = new RetrievedDocumentVO();
		retrievedDocumentVO.setDataHandlerByFilePath(xdsDocumentEntryPO.getUri());
		retrievedDocumentVO.setMimeType(xdsDocumentEntryPO.getMimeType());
		retrievedDocumentVO.setNewDocumentUniqueId(xdsDocumentEntryPO.getUniqueId());
		retrievedDocumentVO.setNewRepositoryUniqueId(xdsDocumentEntryPO.getRepositoryUniqueId());
		return retrievedDocumentVO;

	}
	
}
